<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2023 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\api\validate\SetUserInfoValidate;
use app\common\model\User as UserModel;
use app\api\service\UserService;
use app\common\service\wechat\WeChatMnpService;
use app\common\validate\UserValidate;
use think\facade\Db;

class User extends BaseApi
{
    /**
     * @notes 通过用户ID获取个人信息
     */
    public function infoByUserId()
    {
        $userId = input("user_id");

        $user = UserModel::where(['id' => $userId])->findOrEmpty();

        $user['level'] = UserService::userLevel($user['exp']);

        $user->hidden(['openid', 'unionid']);

        return $this->data($user);
    }

    /**
     * @notes 获取当前登录人信息
     */
    public function info()
    {
        $userId = $this->getUserId();

        $user = UserModel::where(['id' => $userId])->findOrEmpty();

        $user['level'] = UserService::userLevel($user['exp']);

        $user->hidden(['openid', 'unionid']);

        return $this->data($user);
    }

    /**
     * @notes 编辑用户信息
     * @return \think\response\Json
     * @author 段誉
     * @date 2022/9/21 17:01
     */
    public function setInfo()
    {
        $params = (new SetUserInfoValidate())->post()->goCheck();

        $userId = $this->getUserId();

        try {
            if ($params['field'] == 'nickname') {
                $user = UserModel::where('id', $userId)->findOrEmpty();

                if ($user->isEmpty()) {
                    return $this->fail("登录用户不存在");
                }

                //检测账号是否可用
                if ($user->is_disable) {
                    return $this->fail("您的账号异常，请联系客服。");
                }

                $checkText = (new WeChatMnpService())->msgSecCheck($user['openid'], $params["value"]);

                if (!$checkText) {
                    return $this->fail('内容包含敏感文字');
                }
            }

            $result = UserModel::update([
                    'id' => $userId,
                    $params['field'] => $params['value']]
            );

            return $this->success($result);
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * @notes 更新用户头像，昵称，性别
     */
    public function updateUser()
    {
        $params = (new UserValidate())->post()->goCheck("updateUser");

        UserModel::where(['id' => $this->getUserId()])->update([
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'avatar' => $params['avatar']
        ]);

        return $this->success('操作成功');
    }

    //登录用户粉丝列表
    public function userFans()
    {
        $userId = $this->getUserId();
        $followUids = Db::name("follow")->where("follow_uid", $userId)->column("user_id");
        $list = UserModel::where("id", "in", $followUids)->withoutField("password,email,group_id,openid,status,user_type,create_time")->paginate(10)->each(function ($item) use ($userId) {
            $where["user_id"] = $userId;
            $where["follow_uid"] = $item["id"];

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 0; //未关注
            }

            return $item;
        });
        return $this->data($list);
    }

    //登录用户关注列表
    public function follow()
    {
        $userId = $this->getUserId();
        $followUids = Db::name("follow")->where("user_id", $userId)->column("follow_uid");
        $list = UserModel::where("id", "in", $followUids)->withoutField("password,email,group_id,openid,status,user_type,create_time")->paginate(10)->each(function ($item) use ($userId) {
            $where["user_id"] = $item["id"];
            $where["follow_uid"] = $userId;

            $res1 = Db::name("follow")->where($where)->find();

            if ($res1) {
                $item["has_follow"] = 1; //互相关注
            } else {
                $item["has_follow"] = 2; //已关注
            }

            return $item;
        });
        return $this->data($list);
    }


    //添加关注
    public function addFollow()
    {
        $followUserId = input("user_id");
        $loginUserId = $this->getUserId();

        if ($followUserId == $loginUserId) {
            return $this->fail("不能关注自己");
        }

        $find = Db::name("follow")->where(["user_id" => $loginUserId, "follow_uid" => $followUserId])->find();

        if ($find) {
            return $this->fail("您已关注过该用户");
        }

        $res = Db::name("follow")->insert(["user_id" => $loginUserId, "follow_uid" => $followUserId, "create_time" => time()]);
        $nickname = Db::name("user")->where("id", $loginUserId)->value("nickname");

        if ($res) {
            Db::name("user")->where("id", $loginUserId)->inc('follow_num')->update();
            Db::name("user")->where("id", $followUserId)->inc('fans_num')->update();
            \app\common\service\Message::send($loginUserId, $followUserId, 0, 4, "【" . $nickname . "】关注了你");
            return $this->success("关注成功");
        }

        return $this->fail("关注失败");
    }

    //取消关注
    public function cancelFollow()
    {
        $followUserId = input("user_id");
        $loginUserId = $this->getUserId();

        $where["user_id"] = $loginUserId;
        $where["follow_uid"] = $followUserId;
        $res = Db::name("follow")->where($where)->delete();
        if ($res) {
            Db::name("user")->where("id", $loginUserId)->dec('follow_num')->update();
            Db::name("user")->where("id", $followUserId)->dec('fans_num')->update();
            return $this->success("已取消关注");
        }
        return $this->fail("错误");
    }

    //搜索
    public function search()
    {
        $keyword = input("keyword");
        $where[] = ["nickname", "like", "%$keyword%"];
        $list = UserModel::where($where)->paginate(10)->toArray();
        return $this->data($list);
    }
}